import c from 'classnames'
import dayjs from 'dayjs'
import { AvatarImage } from '@/desktop/components'
import SimpleChatRecord from '@/desktop/components/simple-chat-record'
import type { ItemBaseProps } from '@/desktop/logics/contacts'
import services from '@/services'
import { ChatRecordType } from '@/services/contact-chat'
import type { Contact } from '@/services/contacts'
import './content.module.less'

export default function ContactItemContent(
  props: ItemBaseProps & {
    contact: Contact
    avatarExtra?: React.ReactNode
    nameExtra?: React.ReactNode
    side: React.ReactNode
    renderUnread?: (count: number) => React.ReactNode
    className?: {
      item?: string
      current?: string
      inner?: string
      avatar?: string
      name?: string
    }
  },
) {
  const {
    contact,
    ownerCorp,
    ownerQywx,
    isCurrent,
    isTop,
    unread,
    draft,
    style,
    avatarExtra,
    nameExtra,
    side,
    renderUnread,
    className = {},
  } = props

  const onClick = useCallback(() => services.contacts.current.mark(contact), [contact])

  const timeStr = useMemo(() => {
    if (contact.contacted === 0) return ''
    const time = dayjs(contact.contacted)
    const now = dayjs()
    if (time.isAfter(now.startOf('day'))) return time.format('HH:mm')
    if (time.isAfter(now.subtract(1, 'day').startOf('day'))) return '昨天'
    if (time.isAfter(now.startOf('year'))) return time.format('MM-DD')
    return time.format('YYYY-MM')
  }, [contact.contacted])

  return <div
    styleName={c('item', isCurrent && 'current', isTop && 'top')}
    className={c(className.item, isCurrent && className.current)}
    style={style}
    onClick={onClick}
  >
    <div styleName="inner" className={className.inner}>
      <div styleName="avatar" className={className.avatar}>
        <AvatarImage size={42} radius={3} loading="lazy" src={contact.avatar} />
        {unread > 0 ? (
          renderUnread ? (
            renderUnread(unread)
          ) : (
            <span styleName="unread">{unread}</span>
          )
        ) : null}
        {avatarExtra ?? null}
      </div>

      <div styleName="main">
        <div styleName="name-row">
          <div styleName="name" className={className.name}>
            <span>
              {contact.remark ? (
                <>
                  {contact.remark}
                  <span styleName="tip-name">{contact.name}</span>
                </>
              ) : (
                contact.name
              )}
            </span>
            {nameExtra ?? null}
          </div>
          {timeStr.length ? <div styleName="time">{timeStr}</div> : null}
        </div>
        <div styleName="info-row">
          <div styleName="info">
            <div styleName="owner-name">
              {[ownerQywx, ownerCorp].filter(v => v.length).join('-')}
            </div>
            <LatestChat contact={contact} draft={draft} unread={unread} />
          </div>
          <div styleName="side">{side}</div>
        </div>
      </div>
    </div>
  </div>
}

function LatestChat({
  contact,
  draft,
  unread,
}: {
  contact: Contact
  draft: string
  unread: number
}) {
  if (draft) {
    return <div styleName="latest-chat">
      <span styleName="notice">[草稿]</span>
      {draft}
    </div>
  }

  if (contact.latestChat) {
    // 是否是 at 消息并且 at 了自己，且这条消息未读
    const atSelf =
      unread > 0 &&
      contact.latestChat.type === ChatRecordType.Text &&
      !!contact.latestChat.content.atList.find(v => v.userId === contact.ownerWxid)

    return <div styleName="latest-chat">
      {atSelf ? <span styleName="notice">[有人@我]</span> : null}
      <SimpleChatRecord record={contact.latestChat} />
    </div>
  }

  return null
}
